package com.utils;

/**
 * User: oleksandr.baglai
 * Date: 11/19/12
 * Time: 8:40 PM
 */
public class GlassPrinter {

    public static final int GLASS_HEIGHT = 20;
    public static final int GLASS_WIDTH = 10;

    public static String makeBetterPresent(String glass) {
        String result = "";
        for (int i = 0; i < GLASS_HEIGHT; i++) {
            String row = glass.substring(i * GLASS_WIDTH, (i + 1) * GLASS_WIDTH);
            result = row + result;
        }

        return removeSpaces(result);
    }

    private static String removeSpaces(String glass) {
        String result = "";
        boolean emptyLine = true;
        for (int i = 0; i < GLASS_HEIGHT; i++) {
            String row = glass.substring(i * GLASS_WIDTH, (i + 1) * GLASS_WIDTH);
            if (emptyLine && row.equals("          ")) {

            } else {
                emptyLine = false;
                result = result + "\n" + row;
            }
        }

        return result;
    }

    public static String getGlassWithDroppedFigure(String command, String expectedGlassAfterDrop, String figure) {
        CommandParser parser = new CommandParser(command);
        parser.execute();

        if (parser.isDrop()) {
            int x = toX(parser.getLeft(), parser.getRight());
            int y = 19; // на самом верху
            FigureMover mover = new FigureMover(expectedGlassAfterDrop, figure, parser.getRotate(), x, y);
            return mover.getGlass();
        }
        return "";
    }

    public static int toX(int left, int right) {
        if (left > 0) {
            return 4 - left;
        } else {
            return right + 4;
        }
    }

    public static String toString(String command, String figure, int x, int y, String glass) {
        return String.format("Figure: %s, coordinates: (%d, %d), glass %s",
                figure, x, y,
                makeBetterPresent(getGlassWithDroppedFigure(command, glass, figure)));
    }
}
